<?php

$app = new Application();
$app->run();

/**
 * @author Samuel Nogueira <snogueira@rocket-internet.pt>
 */
class Application {
	private $projectFolder;
	
	public function __construct() {
		$this->projectFolder = $_SERVER['argv'][1];
	}
	
	public function run() {
		echo "\n  Total migrations in Array: ".count($this->getMigrations())."\n";
		echo "\n  Total migrations files: ".count($this->getMigrationFiles())."\n";
		
		if ($files = $this->getMigrationFilesNotInArray()) {
			$count = count($files);
			echo "\n  Migration files not in Array: ($count)\n";
			foreach ($files as $file) {
				/* @var $file SplFileInfo */
				echo "  - ".$file->getRealPath()."\n";
			}
			echo "\n";
		}
	}
	
	protected function getMigrationFilesNotInArray() {
		$migrationsArrayFiles = array();
		$out = array();
		
		foreach ($this->getMigrations() as $migration) {
			$module = $migration['module'];
			$fileName = $migration['file'];
			$file = new SplFileInfo("$this->projectFolder/bob/application/modules/$module/migrations/$fileName");
			
			$migrationsArrayFiles[] = $file->getRealPath();
		}
		
		foreach ($this->getMigrationFiles() as $file) {
			/* @var $file SplFileInfo */
			if (!in_array($file->getRealPath(), $migrationsArrayFiles)) {
				$out[] = $file;
			}
		}
		return $out;
	}
	
	protected function getMigrationFiles() {
		$migrationFiles = array();
		$modules = new DirectoryIterator($this->projectFolder.'/bob/application/modules/');
		foreach ($modules as $module) {
			/* @var $module SplFileInfo */
			$migrationsFolder = $module->getRealPath().'/migrations/';
			if (is_dir($migrationsFolder)) {
				$iterator = new RecursiveIteratorIterator(
					new RecursiveDirectoryIterator($migrationsFolder, FilesystemIterator::SKIP_DOTS)
				);
				foreach ($iterator as $file) {
					/* @var $file SplFileInfo */
					if (strpos($file->getRealPath(), '/.svn') !== false) continue;
					$migrationFiles[] = $file;
				}
			}
		}
		return $migrationFiles;
	}
	
	protected function getMigrations() {
		include $this->projectFolder.'/bob/application/configs/migrations.php';
		return $migrations;
	}
}
